import 'dart:convert';

import 'package:ai_data_capture/bean/ConfigFileBean.dart';
import 'package:ai_data_capture/util/JsonUtil.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import 'state.dart';

class EditConfigLogic extends GetxController {
  final EditConfigState state = EditConfigState();
  var controller = TextEditingController();
  late String originText;
  ConfigFileBean? bean;
  late bool isEdit;
  var type = "config".obs;
  @override
  void onInit() {
    super.onInit();
    bean = Get.arguments['bean'] as ConfigFileBean?;
    isEdit = Get.arguments['isEdit'] as bool;

    String content;
    if (bean == null) {
      content = jsonEncode(ConfigFileBean.fromJson({
        "description": "默认配置文件",
        "label_all_true": true,
        "label_duration": 5,
        "label_is_output_unmatch": false,
        "mapping_le_path": "le.pkl",
        "pcap_per_subsection": 2000,
        "pcap_process": 5,
        "pcap_thread_in_process": 70,
        "replace_destination": "replace/dns_label.csv",
        "replace_mapping":
            "destination.port:destination.port;ipProtocol:ipProtocol;protocol:protocol;source.ip:source.ip;source.port:source.port",
        "replace_save_to": "replace/replaced_dns.csv",
        "replace_source":
            "out/abnormal_0816_label.csv,out/abnormal_0830_label.csv",
        "session_alive": "1d",
        "session_all_true": true,
        "session_start_time": "2024-09-12 12:00:00",
        "session_end_time": "2024-09-12 12:01:00",
        "session_expression": "",
        "session_size": 5000,
        "time_session_out": "abnormal_0810_session.csv",
        "splitNumber": 10000,
        "catalogue": "/app/",
      }).toJson());
    } else {
      content = jsonEncode(bean?.toJson());
    }
    if (content.isNotEmpty) {
      var map = jsonDecode(content);
      map.remove('id');
      originText = JsonUtil.unzipJson(map);
      controller.text = originText;
    }
  }

  void insert(String s) {
    var cursorPosition = controller.selection.start;
    controller.value = controller.value.copyWith(
      text: controller.text.replaceRange(cursorPosition, cursorPosition, s),
      selection: TextSelection.collapsed(offset: cursorPosition + s.length),
    );
  }
}
